package wallet

import (
	"context"
	"github.com/jinzhu/copier"
	"github.com/shopspring/decimal"
	"go.uber.org/zap"
	pb2 "navi-mumbai/app/rpc/pay/pb"
	"navi-mumbai/app/rpc/wallet/pb"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/api/business/internal/svc"
	"navi-mumbai/app/api/business/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserDepositLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserDepositLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserDepositLogic {
	return &UserDepositLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserDepositLogic) UserDeposit(req *types.CreateUserDepositReq) (resp *types.CreateUserDepositResp, err error) {
	uid := ctxdata.GetUidFromCtx(l.ctx)
	if uid != req.Uid {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.AuthFail, "no privilege")
	}

	//
	var dCurrencyAmount decimal.Decimal
	dCurrencyAmount, err = decimal.NewFromString(req.CurrencyAmount)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "currency amount error")
	}

	// 创建充值订单
	var in pb.CreateUserDepositReq
	_ = copier.Copy(&in, req)
	in.CurrencyAmount = dCurrencyAmount.StringFixedBank(2)

	var rsp *pb.CreateUserDepositResp
	rsp, err = l.svcCtx.WalletUsersRpc.CreateUserDeposit(l.ctx, &in)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	resp = &types.CreateUserDepositResp{
		FlowNo:         rsp.FlowNo,
		CurrencyAmount: in.CurrencyAmount,
		CurrencyType:   in.CurrencyType,
	}

	// 请求第三方支付
	switch req.PayChannelId {
	case walletkey.PayChannelIdEpay18_UPI:
		var in2 pb2.CreateEpay18DepositReq
		in2.CurrencyAmount = in.CurrencyAmount
		in2.CurrencyType = in.CurrencyType
		in2.FlowNo = rsp.FlowNo
		in2.PayChannelId = req.PayChannelId
		in2.DeviceType = req.DeviceType
		in2.Uid = req.Uid

		var rsp2 *pb2.CreateEpay18DepositResp
		rsp2, err = l.svcCtx.PayUserRpc.CreateEpay18Deposit(l.ctx, &in2)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, err
		}

		resp.PayUrl = rsp2.PayUrl

		var in3 pb.UpdateDepositResultReq
		in3.FlowNo = rsp.FlowNo
		in3.Uid = req.Uid
		in3.State = rsp2.State
		in3.PayGwFlowNo = rsp2.PayGwFlowNo
		in3.ErrMsg = rsp2.ErrMsg
		in3.ExternalFlowNo = rsp2.ExFlowNo
		_, err = l.svcCtx.WalletSysRpc.UpdateDepositResult(l.ctx, &in3)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, err
		}

		if rsp2.State == walletkey.DepositFlowStateFailed {
			return nil, xerr.NewGrpcErrCodeMsg(xerr.ThirdPartRequestError, "pay channel error")
		}
	default:
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "pay channel not support")
	}

	return
}
